using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.IO;
using System.Runtime.InteropServices;
using System.Collections;

namespace VNPT.DoiSoat
{
    public partial class frmDbfFields : DevExpress.XtraEditors.XtraForm
    {
        BinaryReader _Reader;
        ArrayList _fields;
        ArrayList _SelectedFields = new ArrayList();
        string _agrument;
        public string ShowMe(out ArrayList fields, out ArrayList SelectedFields)
        {
            this.ShowDialog();
            fields = _fields;
            SelectedFields = _SelectedFields;
            return _agrument;
        }

        public frmDbfFields(bool Export, string Path, BinaryReader br)
            : this()
        {
            //_Form = f;
            _Reader = br;
            _Export = Export;
            _Path = Path;

        }

        bool _Export;
        string _Path;

        public frmDbfFields()
        {
            InitializeComponent();
            this.Shown += (a, e) => LoadFields();
        }

        private void cmdBack_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Close();
        }

        public void LoadFields()
        {
            DataTable Dt = new DataTable();
            StringBuilder strType = new StringBuilder();
            BinaryReader recReader;
            BinaryReader br;
            br = _Reader;

            Dt.Columns.Add("CHECK", Type.GetType("System.Boolean"));
            Dt.Columns.Add("DBFFIELD", Type.GetType("System.String"));
            Dt.Columns.Add("DBFTYPE", Type.GetType("System.String"));
            Dt.Columns.Add("ORACLEFIELD", Type.GetType("System.String"));

            try
            {
                byte[] buffer = br.ReadBytes(Marshal.SizeOf(typeof(Dbf.DBFHeader)));

                GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
                Dbf.DBFHeader header = (Dbf.DBFHeader)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(Dbf.DBFHeader));
                handle.Free();

                _fields = new ArrayList();
                while ((13 != _Reader.PeekChar()))
                {
                    buffer = br.ReadBytes(Marshal.SizeOf(typeof(Dbf.FieldDescriptor)));
                    handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
                    // fields.Add((Dbf.FieldDescriptor)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(Dbf.FieldDescriptor)));
                    var tem_ = (Dbf.FieldDescriptor)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(Dbf.FieldDescriptor));
                   // if (tem_.FieldName != "_NullFlags")
                    {
                        _fields.Add(tem_);
                    }
                    handle.Free();
                }

                // Read in the first row of records, we need this to help determine column types below
                ((FileStream)br.BaseStream).Seek(header.headerLen + 1, SeekOrigin.Begin);
                buffer = br.ReadBytes(header.recordLen);
                recReader = new BinaryReader(new MemoryStream(buffer));

                foreach (Dbf.FieldDescriptor field in _fields)
                {
                    switch (field.FieldType)
                    {
                        //case 'C':
                        case 'C':
                            strType = new StringBuilder("Character(" + field.FieldLen.ToString() + ")");
                            break;
                        case 'N':
                            strType = new StringBuilder("Numeric(" + field.FieldLen.ToString());
                            if (field.Count > 0)
                            {
                                strType.Append(", " + field.Count.ToString() + ")");
                            }
                            else
                            {
                                strType.Append(")");
                            }
                            break;
                        case 'D':
                            strType = new StringBuilder("Date");
                            break;
                    }
                    DataRow dr = Dt.NewRow();
                    dr["CHECK"] = 1;
                    dr["DBFFIELD"] = field.FieldName;
                    dr["DBFTYPE"] = strType;
                    dr["ORACLEFIELD"] = field.FieldName;
                    Dt.Rows.Add(dr);
                }
            }
            catch { }
            gridControl1.DataSource = Dt;
            br.Close();
        }

        private void cmdNext_Click(object sender, EventArgs e)
        {
            int i = 0, j = 0;
            string stPath = String.Empty;
            

            for (i = 0; i <= gridView1.RowCount - 1; i++)
            {
                if (Convert.ToBoolean(gridView1.GetRowCellValue(i, colChecked)))
                {
                    _SelectedFields.Add(_fields[i]);
                }
            }
            string strPath = _Path;

            //if (!Dbf.CreateControlFile(strPath, _SelectedFields, _fields))
            //{
            //    this.Close();
            //    return;
            //}

            //if (!Dbf.CreateDataFile(Dbf.DbfFile))
            //{
            //    this.Close();
            //    return;
            //}

            this.Close();

            if (_Export)
            //if (_Form.chkExport.CheckState != CheckState.Unchecked)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("Import terminated successfully");
                return;
            }

            var logFile = Path.GetDirectoryName(Application.ExecutablePath) + "\\" + Dbf.FileName + ".log";
            var datFile = Path.GetDirectoryName(Application.ExecutablePath) + "\\" + Dbf.FileName + ".dat";
            var badFile = Path.GetDirectoryName(Application.ExecutablePath) + "\\" + Dbf.FileName + ".bad";
            var ctlFile = Path.GetDirectoryName(Application.ExecutablePath) + "\\" + Dbf.FileName + ".ctl";

            var s = string.Format("userid={0}/{1}@{2} control='{3}' data='{4}'  log='{5}' bindsize=512000 rows=1500000",
                Params.UserName, Params.Password, Params.Database, ctlFile, datFile, logFile);
            _agrument = s;
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.Close();
            //LUUYS         Dbf.BulkInsertWithSqlLoader(s,bgw);
        }

        private void checkEdit1_CheckedChanged(object sender, EventArgs e)
        {
            this.CheckAll(checkEdit1.Checked);
        }

        private void CheckAll(bool flag)
        {
            for (int i = 0; i < gridView1.RowCount; i++)
            {
                gridView1.SetRowCellValue(i, colChecked, flag);
            }
        }

    }
}